package vip.source.pattern.part05;

import java.util.concurrent.atomic.AtomicReference;

/** CAS(线程安全) AtomicReference */
public class Singleton_06 {

    private static final AtomicReference<Singleton_06> INSTANCE =
            new AtomicReference<Singleton_06>();

    private static Singleton_06 instance;

    private Singleton_06() {}

    public static final Singleton_06 getInstance() {
        // for (; ; ) 无限循环，return 后结束
        for (; ; ) {
            Singleton_06 instance = INSTANCE.get();
            if (null != instance) return instance;
            INSTANCE.compareAndSet(null, new Singleton_06());
            return INSTANCE.get();
        }
    }

    public static void main(String[] args) {
        System.out.println(
                Singleton_06.getInstance()); // org.itstack.demo.design.Singleton_06@2b193f2d
        System.out.println(
                Singleton_06.getInstance()); // org.itstack.demo.design.Singleton_06@2b193f2d
    }
}
